import React, {Component} from 'react'
import { withRouter } from 'dva/router'
import styles from './CarConfirmOrder.less'
import { Button, message } from 'antd'
import reduce from 'lodash/reduce'
import { buy as buyBook } from '@/services/book'
import { formatUrlQueryToMap } from '@/utils/utils'
import { connect } from 'dva'


@connect(({ address }) => ({
  address
}))
class CarConfirmOrder extends Component {
  constructor(props){
    super(props)
    this.state = {
      activePayType: "wechat"
    }
  }

  componentDidMount() {
    const alipayParams = formatUrlQueryToMap('out_trade_no')
    const { out_trade_no = '' } = alipayParams
    if (out_trade_no) {
      message.destroy()
      message.success('支付成功')
      setTimeout(() => {
        window.location.href = '/order'
      }, 1000)
    }
  }

  pay() {
    const { address: { addressList }} = this.props
    const { activePayType } = this.state
    const shoppingCar = JSON.parse(localStorage.getItem('shoppingCar')) || []
    const selectIndex = JSON.parse(localStorage.getItem('selectIndex')) || []
    const data = shoppingCar.filter((item, index)=> selectIndex.indexOf(index) > -1)
    let books = data.map(item => {
      return {
        id: item.id,
        amount: item.amount
      }
    })
    // 书籍购买
    // 是否有默认地址
    let hasDefaultAddress = addressList.find(item => item.isDefault)
    if (hasDefaultAddress) {
      let { address, mobile, addressee } = hasDefaultAddress
      buyBook({
        channel: activePayType,
        source: 'web',
        returnUrl: window.location.href,
        address,
        mobile,
        addressee,
        books
      }).then(res => {
        if (res.data.code == 0) {
          let payWindow = window.open();
          payWindow.document.write(res.data.data)
        } else {
          message.error(res.data.msg)
        }
      })
    } else {
      message.error('请添加收获地址')
    }
  }

  setPayType(type) {
    this.setState({
      activePayType: type
    })
  }

  renderTotal(data = []) {
    let totalPrice = reduce(data, (sum, next) => {
        return sum + (next['price'] * next['amount'])
      }, 0)
    return (
      <>
        <div className={styles.priceContainer}>
          <p>¥ {(totalPrice / 100).toFixed(2)}</p>
          <Button type="primary" onClick={this.pay.bind(this)}>
            付款
          </Button>
        </div>
      </>
    )
  }

  render() {
    let { activePayType } = this.state
    const shoppingCar = JSON.parse(localStorage.getItem('shoppingCar')) || []
    const selectIndex = JSON.parse(localStorage.getItem('selectIndex')) || []
    const data = shoppingCar.filter((item, index)=> selectIndex.indexOf(index) > -1)
    return (
      <div className={styles.confirmOrderContainer}>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>购买商品内容</h2>
            {
              data.map((item,index) => {
                return (
                  <div key={index}>
                    <h3 className={styles.productTitle}>{item.title}</h3>
                    <div className={styles.productContainer}>
                      <p>¥ {(item.price / 100).toFixed(2)}</p>
                      <p>X {item.amount}</p>
                    </div>
                  </div>
                )
              })
            }
          </div>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>选择支付方式</h2>
            <div className={styles.imgContainer}>
              <img className={activePayType == 'wechat'? styles.payTypeActive: ''} onClick={(e)=>{this.setPayType.call(this, 'wechat')}} src={require('../../assets/wx.jpg')}/>
              <img className={activePayType == 'alipay'? styles.payTypeActive: ''} onClick={this.setPayType.bind(this,'alipay')} src={require('../../assets/zfb.jpg')}/>
            </div>
          </div>
          <div className={styles.textContainer}>
            <h2 className={styles.title}>支付金额</h2>
            { this.renderTotal(data) }
          </div>
      </div>
    );
  }
}

export default withRouter(CarConfirmOrder);